package com.xd.common.exception;

import cn.hutool.core.util.StrUtil;

import java.util.Collection;
import java.util.function.Function;

/**
 *
 */
public class Assert {
    /**
     * null/false/""/empty 无-->抛异常
     *
     * @param target
     * @param message
     */
    public static <T> T no(T target, String message) {
        return no(target, message, XkdException::new);
    }

    /**
     * true/!empty/!null 有-->抛异常
     *
     * @param target
     * @param message
     */
    public static <T> void yes(T target, String message) {
        yes(target, message, XkdException::new);
    }

    /**
     * null/false/""/empty/<=0 无-->抛指定异常
     *
     * @param target
     * @param message  异常信息
     * @param function 指定异常
     */
    public static <T> T no(T target, String message, Function<String, RuntimeException> function) {
        if (isNo(target))
            throw function.apply(message);
        return target;
    }

    /**
     * !null/true/"--"/!empty/>0 有-->抛指定异常
     *
     * @param target
     * @param message  异常信息
     * @param function 指定异常
     */
    public static <T> void yes(T target, String message, Function<String, RuntimeException> function) {
        if (isYes(target))
            throw function.apply(message);
    }

    public static <T> Boolean isNo(T target) {
        return null == target
                || (target instanceof Boolean && !(Boolean) target)
                || (target instanceof String && StrUtil.isBlank((String) target))
                || (target instanceof Integer && (Integer) target <= 0)
                || (target instanceof Collection && ((Collection<?>) target).isEmpty());
    }

    public static <T> Boolean isYes(T target) {
        return !isNo(target);
    }
}

